import React from "react";
import "../style/index.css"

class CommentListTemplate extends React.Component {

    state = {
        comments: [
            {id: 1, name: 'jack', content: '沙发！！！'},
            {id: 2, name: 'rose', content: '板凳~'},
            {id: 3, name: 'tom', content: '楼主好人'}
        ],
        userName: '',
        userContent: ''
    };


    renderList() {
        if (this.state.comments.length === 0) {
            return (<div className="no-comment">暂无评论，快去评论吧</div>)
        } else {
            return (
                <ul> {
                    this.state.comments.map(item => {
                        return (
                            <li key={item.id}>
                                <h3>{item.name}</h3>
                                <p>{item.content}</p>
                            </li>
                        )
                    })
                }
                </ul>
            )
        }
    };

    // 在`handleFrom`函数中利用`setState`来让数据保持一致
    handleForm = (e) => {
        this.setState({
            [e.target.name]: e.target.value
        })
    };

    handleClick = (e) => {
        //拿到用户输入的值
        let {userName, userContent} = this.state;
        if (userName.trim() === '' || userContent.trim() === '') {
            alert("请输入内容")
            return;
        }

        let newComments = [{
            id: this.state.comments.length+1,
            name: userName,
            content: userContent
        },...this.state.comments]

        this.setState({
            comments: newComments,
            userName:'',
            userContent: ''
        })
    }

    // eslint-disable-next-line react/require-render-return
    render() {
        return (
            <div>
                <div className="app">
                    <div>
                        <input className="user" type="text" placeholder="请输入评论人" value={this.state.userName}
                               name="userName" onChange={this.handleForm}/><br/>

                        <textarea className="content" cols="30" rows="10" placeholder="请输入评论内容"
                                  value={this.state.userContent} name="userContent" onChange={this.handleForm}/><br/>

                        <button onClick={this.handleClick}>发表评论</button>
                    </div>
                    {/* 通过条件渲染来判断是否显示暂无评论 */}
                    {this.renderList()}
                </div>
            </div>
        );
    }
}


export default CommentListTemplate;